﻿using UnityEngine;
using UnityEditor;
using System.Collections;

public class MiniSvn
{
    #region - SVN -

    [MenuItem("Assets/SVN/showlog")]
    static void ExternalSvnShowLog()
    {
        SvnShowLog(GetCurProjectObjPath());
    }
    [MenuItem("Assets/SVN/add")]
    static void ExternalSvnAdd()
    {
        SvnAdd(GetCurProjectObjPath());
    }
    [MenuItem("Assets/SVN/commit")]
    static void ExternalSvnCommit()
    {
        SvnCommit(GetCurProjectObjPath());
    }
    [MenuItem("Assets/SVN/update")]
    static void ExternalSvnUpdate()
    {
        SvnUpdate(GetCurProjectObjPath());
    }

    static string GetCurProjectObjPath()
    {
        if (null == Selection.objects || Selection.objects.Length != 1) return string.Empty;

        string path = AssetDatabase.GetAssetPath(Selection.objects[0].GetInstanceID());
        if (!string.IsNullOrEmpty(path))
        {
            path = System.IO.Path.GetFullPath(path);
        }
        return path;
    }

    #endregion

    private const string SVN_EXE_PATH = "C:\\Program Files\\TortoiseSVN\\bin\\TortoiseProc.exe";

    public static void SvnShowLog(string filePath)
    {
        string args = "/command:log /path:" + filePath + " /closeonend:0";
        // 快捷方式
        System.Diagnostics.Process.Start(SVN_EXE_PATH, args);
        // cmd方式
        //string[] cmdArray = new string[]
        //{
        //    "cd C:\\Program Files\\TortoiseSVN\\bin\\",
        //    "TortoiseProc.exe" + " " + args,
        //};
        //RunCmd(cmdArray);
    }

    public static void SvnAdd(string filePath)
    {
        string addRes = filePath;
        if (System.IO.File.Exists(filePath))
        {
            addRes = System.IO.Path.GetDirectoryName(filePath);
        }
        string args = "/command:add /path:" + addRes + " /closeonend:0";
        System.Diagnostics.Process.Start(SVN_EXE_PATH, args);
    }

    public static void SvnCommit(string filePath)
    {
        string args = "/command:commit /path:" + filePath + " /logmsg:res: ui" + " /closeonend:0";
        System.Diagnostics.Process.Start(SVN_EXE_PATH, args);
    }

    public static void SvnUpdate(string filePath)
    {
        string args = "/command:update /path:" + filePath + " /closeonend:0";
        System.Diagnostics.Process.Start(SVN_EXE_PATH, args);
    }

    private static void RunCmd(string[] cmds)
    {
        System.Diagnostics.Process proc = new System.Diagnostics.Process();
        proc.StartInfo.CreateNoWindow = true;
        proc.StartInfo.FileName = "cmd.exe";
        proc.StartInfo.UseShellExecute = false;
        proc.StartInfo.RedirectStandardError = true;
        proc.StartInfo.RedirectStandardInput = true;
        proc.StartInfo.RedirectStandardOutput = true;
        proc.Start();
        foreach (string cmd in cmds)
        {
            proc.StandardInput.WriteLine(cmd);
        }
        proc.WaitForExit();
        proc.Close();
    }
}
